import useRequest from '../composables/useRequest.js'
import { ref, onMounted, watch } from 'vue'
const todos = ref([]);
const orderBy = ref('asc');
export default () => {
    const request = useRequest();
    // setup本身就是一个异步，所以不需要onMounted
    // onMounted(() => {
    //   todos.value = await fetch(`http://127.0.0.1:3005/news`).then(r => r.json());
    // });
    
    // todos.value = await fetch(`http://127.0.0.1:3005/news`).then(r => {
    //     return new Promise(resolve => {
    //     setTimeout(() => resolve(r.json()),2000)
    //     })
    // });

    const load = async () => {
        todos.value = await request.get();
        sort();
    };

    const del = async (id) => {
        await request.delete(id);
        load();
    }

    const add = async (todo) => {
        await request.post(todo);
        load();
    }

    const sort = () => {
        todos.value = Array.prototype.sort.call(todos.value,(a,b) => {
            return (orderBy.value == 'asc') ? (a.id - b.id) : (b.id - a.id);
        })
    }
    watch(orderBy,() => sort())
    return {todos,del,load,add,orderBy};
}